package com.luocc.ccdemo.utils

import android.os.Bundle
import android.util.Log
import com.luocc.ccdemo.entity.Blog
import com.luocc.ccdemo.entity.Result
import com.luocc.ccdemo.entity.User
import com.luocc.ccdemo.entity.Video
import org.json.JSONObject
import java.net.URL

object Api {
    private const val TAG = "LC_Api"

    private const val BASE_VIDEO = "https://api.apiopen.top/api"
    private const val BASE_WAN = "https://www.wanandroid.com"

    private const val WAN_CODE = "errorCode"
    private const val WAN_MSG = "errorMsg"
    private const val WAN_DATA = "data"

    private const val OPEN_CODE = "code"
    private const val OPEN_LIST = "list"
    private const val OPEN_TOTAL = "total"
    private const val OPEN_RESULT = "result"
    private const val OPEN_MESSAGE = "message"

    private const val V_ID = "id"
    private const val V_TITLE = "title"
    private const val V_USER_PIC = "userPic"
    private const val V_USERNAME = "userName"
    private const val V_VIDEO_URL = "playUrl"
    private const val V_DURATION = "duration"
    private const val V_COVER_URL = "coverUrl"

    fun register(username: String, password: String, rePassword: String): Result<Boolean> {
        val result = Result<Boolean>()
        val url =
            URL("${BASE_WAN}/user/register?username=${username}&password=${password}&repassword=${rePassword}")
        val response = OkHttpUtil.post(url, HashMap())
        if (response.isSuccessful) {
            response.body?.string()?.let {
                val jsonObject = JSONObject(it)
                val code = jsonObject.getInt(WAN_CODE)
                val message = jsonObject.getString(WAN_MSG)
                result.code = code
                result.message = message
            }
        }
        return result
    }

    fun login(user: User): Result<String> {
        val result = Result<String>()
        val url = URL("${BASE_WAN}/user/login?username=${user.username}&password=${user.password}")
        val response = OkHttpUtil.post(url, HashMap())
        if (response.isSuccessful) {
            response.body?.string()?.let {
                val jsonObject = JSONObject(it)
                val code = jsonObject.getInt(WAN_CODE)
                val message = jsonObject.getString(WAN_MSG)
                result.code = code
                result.message = message
            }
        }
        return result
    }

    fun logout(): Result<Boolean> {
        val result = Result<Boolean>()
        val url = URL("$BASE_WAN/user/logout/json")
        val response = OkHttpUtil.get(url)
        if (response.isSuccessful) {
            response.body?.string()?.let {
                val jsonObject = JSONObject(it)
                val code = jsonObject.getInt(WAN_CODE)
                val message = jsonObject.getString(WAN_MSG)
                result.code = code
                result.message = message
            }
        } else {
            result.code = -1
            result.message = "退出账号异常"
        }
        return result
    }

    /**
     * @param pageSize 不要变，否则需要重新计数
     */
    fun getBlogs(pagination: Int = 0, pageSize: Int = -1): Result<Bundle> {
        val result = Result<Bundle>()
        val bundle = Bundle(2)
        val url = if (pageSize >= 0) {
            URL("$BASE_WAN/user_article/list/$pagination/json?page_size=$pageSize")
        } else {
            URL("$BASE_WAN/user_article/list/$pagination/json")
        }
        val response = OkHttpUtil.get(url)
        if (response.isSuccessful) {
            response.body?.string()?.let {
                val jsonObject = JSONObject(it)
                val code = jsonObject.getInt(WAN_CODE)
                val message = jsonObject.getString(WAN_MSG)
                result.code = code
                result.message = message

                val data = jsonObject.getJSONObject(WAN_DATA)
                val curPage = data.getInt("curPage")
                val list = data.getJSONArray("datas")
                val blogs = ParseUtil.parseBlog(list)
                bundle.putInt("curPage", curPage)
                bundle.putParcelableArrayList("blogs", blogs)
                result.data = bundle
            }
        } else {
            result.code = -1
            result.message = "退出账号异常"
        }
        return result
    }

    fun getHaoKanVideo(page: Int, size: Int): Result<Bundle> {
        Log.d(TAG, "getHaoKanVideo ${Throwable().message}")
        val result = Result<Bundle>()
        val url = URL("${BASE_VIDEO}/getHaoKanVideo?page=$page&size=$size")
        val response = OkHttpUtil.get(url)
        if (response.isSuccessful) {
            response.body?.string()?.let {
                val jsonObject = JSONObject(it)
                result.code = jsonObject.getInt(OPEN_CODE)
                result.message = jsonObject.getString(OPEN_MESSAGE)
                if (result.code == 200) {
                    val bundle = parseVideoResponse(jsonObject)
                    result.data = bundle
                }
            }
        } else {
            result.code = -1
            result.message = "获取视频失败"
        }
        return result
    }

    private fun parseVideoResponse(jsonObject: JSONObject): Bundle {
        val bundle = Bundle()
        val result = jsonObject.getJSONObject(OPEN_RESULT)
        bundle.putInt(OPEN_TOTAL, result.getInt(OPEN_TOTAL))
        val list = result.getJSONArray(OPEN_LIST)
        val videos = ArrayList<Video>()
        for (index in 0 until list.length()) {
            val v = list[index] as JSONObject
            val video = Video(
                v.getInt(V_ID),
                v.getString(V_TITLE),
                v.getString(V_COVER_URL),
                v.getString(V_VIDEO_URL),
                v.getString(V_DURATION),
                v.getString(V_USERNAME),
                v.getString(V_USER_PIC),
                null,
                null,
                null
            )
            videos.add(video)
        }
        bundle.putParcelableArrayList("videos", videos)
        return bundle
    }
}